package com.aichan.aibi.service.impl.UserDetails;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.aichan.aibi.mapper.PermissionMapper;
import com.aichan.aibi.mapper.RoleMapper;
import com.aichan.aibi.mapper.UserMapper;
import com.aichan.aibi.model.entity.Permission;
import com.aichan.aibi.model.entity.Role;
import com.aichan.aibi.model.entity.User;
import com.aichan.aibi.model.entity.login.LoginUser;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;

/**
 * Spring Security 中 UserDetailsService自定义实现类
 * @author mengyu
 * @date 2024/03/03 9:32
 */
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("loadUserByUsername:{}",username);
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>()
                .eq(User::getUserAccount, username);
        User user = userMapper.selectOne(lqw);
        if(user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);
        // 设置Role和Permission
        List<Role> roles = roleMapper.listRoleByUserId(user.getId());
        List<Permission> permissions = permissionMapper.listPermissionByRoleId(user.getId());
        loginUser.setRoles(roles);
        loginUser.setPermissions(permissions);
        return loginUser;
    }
}
